package boardgamer.common.client.preference;

import android.content.SharedPreferences;
import android.preference.Preference;

import static com.google.common.base.Preconditions.checkNotNull;

/**
* @author garysoed
*/
public abstract class AbstractRegisteredPreference<V, P extends Preference> {

  protected final String key;
  protected final P preference;
  protected final V defaultValue;
  protected final Class<V> valueClass;
  protected final SharedPreferences sharedPreferences;

  protected AbstractRegisteredPreference(String key, P preference, V defaultValue,
      SharedPreferences sharedPreferences) {
    this.key = checkNotNull(key, "key");
    this.preference = checkNotNull(preference, "preference");
    this.defaultValue = checkNotNull(defaultValue, "defaultValue");
    this.valueClass = (Class<V>)defaultValue.getClass();
    this.sharedPreferences = checkNotNull(sharedPreferences, "sharedPreferences");
  }

  public final void update(Object newValue) {
    setValue(valueClass.cast(newValue));
  }

  public final void refresh() {
    setValue(getFromSharedPreferences());
  }

  protected abstract V getFromSharedPreferences();

  public abstract void setValue(V newValue);
}
